package net.lesscoding.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import net.lesscoding.message.*;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author eleven
 * @date 2024/10/31 14:55
 * @apiNote
 */
@Slf4j
public class ClientChannelAdapter extends ChannelInboundHandlerAdapter {
    CountDownLatch latch = new CountDownLatch(1);
    AtomicBoolean flag = new AtomicBoolean();
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        new Thread(() -> {
            // 接收用户在客户端的输入，负责发送各种数据
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入用户名和密码");
            String username = scanner.nextLine();
            System.out.println("请输入密码");
            String password = scanner.nextLine();
            Message message = new LoginRequestMessage(username, password);
            // 发送消息
            ctx.writeAndFlush(message);
            System.out.println("等待后续操作");
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (!flag.get()) {
                ctx.channel().close();
                return;
            }
            while (true) {
                System.out.println("=========================================");
                System.out.println("send [username] [content]");
                System.out.println("gsend [group name] [content]");
                System.out.println("gcreate [group name] [m1,m2,m3...]");
                System.out.println("gmembers [group name]");
                System.out.println("gjoin [group name]");
                System.out.println("gquit [group name]");
                System.out.println("quit");
                System.out.println("=========================================");
                String command = scanner.nextLine();
                String[] split = command.split(" ");

                switch (split[0]) {
                    case "send":
                        // 发送消息
                        ctx.writeAndFlush(new ChatRequestMessage(username, split[1], split[2]));
                        break;
                    case "gsend":
                        // 发送群消息
                        ctx.writeAndFlush(new GroupChatRequestMessage(username, split[1], split[2]));
                        break;
                    case "gcreate":
                        // 创建群聊
                        Set<String> split1 = new HashSet<>(Arrays.asList(split[2].split(",")));
                        ctx.writeAndFlush(new GroupCreateRequestMessage(split[1], split1));
                        break;
                    case "gmembers":
                        // 查看群聊成员
                        ctx.writeAndFlush(new GroupMembersRequestMessage(split[1]));
                        break;
                    case "gjoin":
                        // 加入群聊
                        ctx.writeAndFlush(new GroupJoinRequestMessage(username, split[1]));
                        break;
                    case "gquit" :
                        // 退出群聊
                        ctx.writeAndFlush(new GroupQuitRequestMessage(username, split[1]));
                        break;
                    case "quit":
                        // 退出
                        ctx.channel().close();
                        return;
                    default:
                        System.out.println("无法识别[" + command + "]指令，请重新输入！");
                        break;
                }
            }
        }).start();
        // 在连接建立后发送消息
        super.channelActive(ctx);
    }

    /**
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.debug("收到服务端的消息：{}", msg);
        if (msg instanceof LoginResponseMessage) {
            LoginResponseMessage response = (LoginResponseMessage) msg;
            if (response.isSuccess()) {
                flag.set(true);
            } else {
                System.out.println("登录失败，原因：" + response.getReason());
                flag.set(false);
            }
        }
        latch.countDown();
        super.channelRead(ctx, msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
